package com.ledtechdesign.auth;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ledtechdesign.afcs.IAuthToken;
import com.ledtechdesign.afcs.IRole;
import com.ledtechdesign.beans.Session;
import com.ledtechdesign.beans.User;
import com.ledtechdesign.service.Utils;

public class AuthenticationFactory {

	private static IAuthToken authToken;
	
	public static Log logger = LogFactory.getLog(AuthenticationFactory.class);
	
	private static final String regUserTokenPrefix="gak";
	private static final String guestUserTokenPrefix="guk";
	private static final String extAuthTokenPrefix="exx";

	public static IAuthToken getAuthToken(String token) {
		// TODO
		return new DefaultAuthToken(token,regUserTokenPrefix,false);
	}
	
	private static Map<String, IAuthToken> tokens ;
	
	static {
		tokens = new HashMap<String, IAuthToken>(3);
	}

	public static IAuthToken getSessionAuthToken(User user, Session session) {
		// TODO
		
		if (user.getRole() < IRole.NONE || user.getRole() > IRole.OWNER)
			throw new Error("invalid-role");

		try {
			String token = "x:" + user.getName() + "::"
			+ session.getAccount().getAccountName() + ":" + user.getId()
			+ ":" + session.getRoom() + ":"
			+ Integer.toString(user.getRole());
			logger.debug("External Auth token String: " + token);

			String signed = token
			+ ":"
			+ Utils.sign(session.getAccount().getSecret(),session.getSessionSecret() , token);
			logger.debug("External Auth token accountSecret: "
			+ session.getAccount().getSecret() + " signed: " + signed);
			
			IAuthToken t = new DefaultAuthToken(signed,extAuthTokenPrefix,false);
			return t;
			
			//return new SessionAuthToken(user, session);
		} catch (Exception e) {

			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public static IAuthToken getGuestAuthToken(String token) {
		// TODO
		return new DefaultAuthToken(token,guestUserTokenPrefix,true);
	}

}
